package com.jinzheng.qianhai.commont;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.header.Header;
import org.apache.kafka.common.header.internals.RecordHeader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.stereotype.Component;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutionException;

/**
 * kafka生产者
 */
@Component
@Slf4j
public class KafkaProducer {

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;

    /**
     * 发送消息
     */
    public void sendMessage() {
        try{
            //生产消息
            String message = "hello ！ 测试kafka ";
            ListenableFuture<SendResult<String, String>> listenableFuture = kafkaTemplate.send("hello","hello", message);
            listenableFuture.addCallback(new ListenableFutureCallback<SendResult<String, String>>() {
                @Override
                public void onSuccess(SendResult<String, String> result) {
                    System.out.println("sendMessage success");
                }
                @Override
                public void onFailure(Throwable ex) {
                    System.out.println("sendMessage error");
                }
            });
        }catch (Exception e){
            System.out.println("sendMessage exception");
        }

    }

    /**
     * 发送消息
     */
    public void sendMessageByTopic(String topic,String headName,String message) {
        String headerName = StringUtils.EMPTY;
        if(StringUtils.isBlank(headName)){
            headerName = "test_socket_header";
        }else{
            headerName = headName;
        }
        List<Header> headers = Arrays.asList(new RecordHeader("header_name", headerName.getBytes()));
        ProducerRecord producerRecord = new ProducerRecord(topic,null, "", message, headers);
        try {
            kafkaTemplate.send(producerRecord).get();
            log.info(String.format("\n发送数据成功，topic->%s,\n发送表头->%s\n数据格式->%s",topic,headerName,JSONObject.toJSONString(message, SerializerFeature.WriteMapNullValue,SerializerFeature.WriteDateUseDateFormat)));
        } catch (InterruptedException e) {
            String errMessage = e.getMessage();
            if(StringUtils.isBlank(errMessage)){
                errMessage = e.toString().length()>3000?e.toString().substring(0,2800):e.toString();
            }
            log.error(String.format("\n发送数据失败，topic->%s,\n发送表头->%s\n数据格式->%s\n异常原因->%s",topic,headerName,JSONObject.toJSONString(message, SerializerFeature.WriteMapNullValue,SerializerFeature.WriteDateUseDateFormat),errMessage));
            e.printStackTrace();
        } catch (ExecutionException e) {
            String errMessage = e.getMessage();
            if(StringUtils.isBlank(errMessage)){
                errMessage = e.toString().length()>3000?e.toString().substring(0,2800):e.toString();
            }
            log.error(String.format("\n发送数据失败，topic->%s,\n发送表头->%s\n数据格式->%s\n异常原因->%s",topic,headerName,JSONObject.toJSONString(message, SerializerFeature.WriteMapNullValue,SerializerFeature.WriteDateUseDateFormat),errMessage));
            e.printStackTrace();
        }finally {
            log.info(String.format("\n发送数据格式，topic->%s,\n发送表头->%s\n数据格式->%s",topic,headerName,JSONObject.toJSONString(message, SerializerFeature.WriteMapNullValue,SerializerFeature.WriteDateUseDateFormat)));
        }
    }
}

